<template>
  <div class="app-container">
    <NormalForm pageTitle="用户管理" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt"
      @handleQuery="handleQuery" @handleReset="handleReset" />
    <div class="g-card" style="margin-top: 16px">
      <div style="padding:20px">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick" :before-leave="handleTabBefore">
          <el-tab-pane label="新增账户列表" name="1">
            <el-table v-loading="loading" :data="userList" height="410px">
              <el-table-column label="用户编号" align="center" prop="userId" />
              <el-table-column label="账户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
              <el-table-column label="用户昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
              <el-table-column label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />
              <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
              <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                    v-has-permi="['system:user:state']" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:user:edit']">修改</el-button>
                  <el-button v-if="scope.row.userId !== 1" size="mini" type="text" icon="el-icon-delete"
                    @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                  <el-button size="mini" type="text" icon="el-icon-key" plain @click="changeResPassword(scope.row)"
                    v-hasPermi="['system:user:reset']">重置</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="邀请员工列表" name="2">
            <el-table v-loading="loading" :data="userList" height="410px">
              <el-table-column label="用户编号" align="center" prop="userId" />
              <el-table-column label="账户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
              <!-- <el-table-column label="用户昵称" align="center" prop="nickName" :show-overflow-tooltip="true" /> -->
              <el-table-column label="用户昵称" align="center" prop="userName" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-button size="mini" type="text">
                    {{ scope.row.invitateType == '1' ? scope.row.nickName : '/' }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="岗位" align="center" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ (scope.row.poseList && scope.row.poseList.map(item => item.name).toString()) || ''
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="角色" align="center" :show-overflow-tooltip="true" width="60">
                <template slot-scope="scope">
                  <span>{{ (scope.row.roleList && scope.row.roleList.map(item => item.name).toString()) || ''
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="关联员工" align="center" prop="weUserName" width="100" />
              <el-table-column label="状态" align="center" width="80">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                    :disabled="scope.row.invitateType != 1" v-has-permi="['system:user:state']"
                    @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="是否填写用户信息" align="center" width="130">
                <template slot-scope="scope">
                  <span v-if="scope.row.invitateType == 1">已填写</span>
                  <span v-else-if="scope.row.invitateType == 2">未填写</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:user:edit']" :disabled="scope.row.invitateType != 1"
                    :style="{ 'color': scope.row.invitateType != 1 ? '#ccc !important' : '#082aff !important' }">修改
                  </el-button>
                  <el-button v-if="scope.row.userId !== 1" size="mini" type="text" icon="el-icon-delete"
                    @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"
                    :disabled="scope.row.invitateType != 1"
                    :style="{ 'color': scope.row.invitateType != 1 ? '#ccc !important' : '#082aff !important' }">删除
                  </el-button>
                  <el-button size="mini" type="text" icon="el-icon-key" plain @click="changeResPassword(scope.row)"
                    v-hasPermi="['system:user:reset']" :disabled="scope.row.invitateType != 1"
                    :style="{ 'color': scope.row.invitateType != 1 ? '#ccc !important' : '#082aff !important' }">重置
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="CustoBtn">
            <div slot="label">
              <el-button v-if="activeTab == '1'" type="primary" @click="handleAdd"
                v-hasPermi="['system:user:add']">新增账户</el-button>
              <el-button v-else type="primary" @click="inviteStaffFn">邀请员工</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
        <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
          @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
    </div>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="updateVisible" width="800px" append-to-body v-loading="addingPopover"
      :close-on-click-modal="false">
      <el-form ref="updateForm" :model="updateForm" :rules="updateRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="updateForm.nickName" placeholder="请输入用户昵称" style="width: 280px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="updateForm.deptId" :options="enumOpt.manageComList" :disable-branch-nodes="true"
                :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="updateForm.phonenumber" placeholder="请输入手机号码" maxlength="11" style="width: 280px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="updateForm.email" placeholder="请输入邮箱" maxlength="50" style="width: 280px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title === '添加用户'">
            <el-form-item label="账户名称" prop="userName">
              <el-input v-model="updateForm.userName" placeholder="请输入账户名称" style="width: 280px;" autocomplete="off"/>
            </el-form-item>
          </el-col>
          <el-col :span="12"  v-if="title === '添加用户'">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="updateForm.password" placeholder="请输入用户密码" type="password" style="width: 280px;" autocomplete="off" show-password/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道" prop="insuranceType">
              <el-select v-model="updateForm.insuranceType" placeholder="请选择渠道" style="width: 280px;">
                <el-option v-for="dict in insurancesList" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="updateForm.status">
                <el-radio v-for="item in enumOpt.stateList" :key="item.dictValue" :label="item.dictValue">{{
                  item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postIds">
              <el-select v-model="updateForm.postIds" multiple placeholder="请选择岗位" style="width: 280px;">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="updateForm.roleIds" multiple placeholder="请选择用户角色" style="width: 280px;">
                <el-option v-for="item in enumOpt.roleList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="updateForm.sex" placeholder="请选择用户性别" style="width: 280px;">
                <el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级权限" prop="level">
              <el-select v-model="updateForm.level" placeholder="请选择客户信息等级" style="width: 280px;">
                <el-option v-for="item in levelList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联员工" prop="weUserId">
              <el-button class="button-new-tag" size="small" @click="openStaff" v-model="updateForm.weUserId">
                <svg-icon icon-class="add" />关联员工
              </el-button>
              <div v-if="scrmPersonSopUserRels">
                <el-tag closable @close="handleClose(item)" v-for="item in scrmPersonSopUserRels" :key="item.userId">
                  {{ item.userName }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="updateForm.remark" type="textarea" placeholder="请输入内容" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="updateCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改密码弹窗 -->
    <el-dialog title="重置密码" :visible.sync="resetPwdVisible" width="600px" :close-on-click-modal="false">
      <el-form label-width="140px" :rules="resRules" ref="resForm" :model="resForm">
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="resForm.newPwd" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="resetPwdVisible = false">取 消</el-button>
        <el-button @click="handleResetPwd" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 邀请弹窗 -->
    <el-dialog title="邀请员工" :visible.sync="inviteVisible" width="580px" :close-on-click-modal="false">
      <el-form label-width="80px" :rules="inviteRules" ref="inviteForm" :model="inviteForm">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="inviteForm.mobile" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
        <el-form-item label="账户名称" prop="name">
          <el-input v-model="inviteForm.name" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="岗位" prop="postIds">
          <el-select v-model="inviteForm.postIds" multiple placeholder="请选择">
            <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
              :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="inviteForm.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in enumOpt.roleList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联员工" prop="weUserId">
          <el-button v-model="inviteForm.weUserId" class="button-new-tag" size="small" @click="openStaff">
            <svg-icon icon-class="add" />
            关联员工
          </el-button>
          <div v-if="scrmPersonSopUserRels">
            <el-tag closable @close="handleClose(item)" v-for="item in scrmPersonSopUserRels" :key="item.userId">
              {{ item.userName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="inviteForm.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="inviteCancel">取 消</el-button>
        <el-button @click="inviteSubmit" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 选择员工弹窗 -->
    <SelectUser title="添加员工" :selectList="selectList" :visible.sync="staffDialog" @confirm="selectUserConfirm"
      :is-active="'0'"></SelectUser>
  </div>
</template>

<script>
import { listRole, } from '@/api/system/role'
import { addUser, changeUserStatus, delUser, inviteUser, getUser, listUser, resetUserPwd, updateUser } from '@/api/system/user'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { resetForm } from '@/utils/common'
import SelectUser from "@/components/SelectUser/index.vue";
import { createdCascader } from '@/components/index.js'
import Cookies from 'js-cookie'
import { permission } from "@/api/communityOperating/personalSop.js";

export default {
  name: 'User',
  components: { Treeselect, SelectUser, createdCascader },
  data() {
    return {
      activeTab: '1',
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      //险种
      insurancesList: [],
      queryForm: {
        userName: '',
        phonenumber: null,
        status: null,
        deptId: null,
        dateRange: [],
        createList: null,
        weUserName: '',
        roleId: null,
        pageNum: 1,
        pageSize: 20,
      },
      formList: [
        {
          label: '账户名称',
          value: '',
          prop: 'userName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '手机号码',
          value: '',
          prop: 'phonenumber',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '员工姓名',
          value: '',
          prop: 'weUserName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '机构',
          value: '',
          prop: 'deptId',
          type: 'SINGLE_MANAGE_COM',
          emunName: 'manageComList'
        },
        {
          label: '角色',
          value: '',
          prop: 'roleId',
          type: 'SELECT',
          emunName: 'roleList'
        },
        {
          label: '用户状态',
          value: '',
          prop: 'status',
          type: 'SELECT',
          emunName: 'stateList'
        },
        {
          label: '创建人',
          value: '',
          prop: 'createList',
          type: 'SELECT',
          emunName: 'staffList'
        },
        {
          label: '创建',
          value: null,
          prop: 'dateRange',
          type: 'DATE_RANGE',
          emunName: '',
          formate: 'yyyy-MM-dd'
        },
      ],
      enumOpt: {
        manageComList: [],
        roleList: [],
        stateList: [],
        staffList: [],
      },
      loading: true,
      total: 0,
      userList: [],
      // 新增、更新账户
      title: '',
      updateVisible: false,
      updateForm: {
        deptId: null,
        email: '',
        insuranceType: '',
        nickName: '',
        password: '',
        phonenumber: '',
        postIds: [],
        remark: '',
        roleIds: [],
        sex: '',
        status: '',
        userName: '',
        weUserId: '',
        weUserName: '',
        level: '',
      },
      levelList: [],
      updateRules: {
        userName: [
          { required: true, message: '账户名称不能为空', trigger: 'blur' },
          { min: 4, message: '账户名称不能小于4位', trigger: 'blur' },
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '归属部门不能为空', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '关联角色不能为空', trigger: 'blur' }
        ],
        postIds: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          {
            pattern: /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,20}$/,
            message: '密码请输入8-20位大小写字母、数字、特殊符号组合！',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          {
            type: 'email',
            message: '\'请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phonenumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        weUserId: [
          { required: true, message: '关联员工不能为空', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '等级权限不能为空', trigger: 'blur' }
        ],
      },
      scrmPersonSopUserRels: [],
      // 重置密码
      resetPwdVisible: false,
      pwdUserId: '',
      resForm: {
        newPwd: ''
      },
      resRules: {
        newPwd: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          {
            pattern: /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,20}$/,
            message: '密码请输入8-20位大小写字母、数字、特殊符号组合！',
            trigger: 'blur'
          }
        ]
      },
      inviteVisible: false,
      staffList: '', // 第二列勾选内容
      staffDialog: false,
      selectList: [], // 选择人员
      weUserId: '',
      addingPopover: false,
      // 默认密码
      initPassword: undefined,
      inviteForm: {
        userId: '',
        mobile: '',
        name: '',
        postIds: [],
        roleIds: [],
        weUserId: '',
        weUserName: '',
        remark: '',
        url: ''
      },
      inviteRules: {
        name: [{ required: true, message: '账户名称不能为空', trigger: 'blur' },
        { min: 4, message: '账户名称不能小于4位', trigger: 'blur' },],
        mobile: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        deptId: [{ required: true, message: '归属部门不能为空', trigger: 'blur' }],
        roleIds: [{ required: true, message: '关联角色不能为空', trigger: 'blur' }],
        postIds: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
        weUserId: [{ required: true, message: '关联员工不能为空', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getTreeselect()
    this.getEnumList()
    this.handleQuery()
  },
  methods: {
    // 获取枚举值
    getEnumList() {
      this.getDicts('insurance_type').then((res) => {
        if (res.code == 200) this.insurancesList = res.data
      })
      this.getDicts('sys_user_sex').then((res) => {
        if (res.code == 200) this.sexOptions = res.data
      })
      this.getConfigKey('sys.user.initPassword').then((res) => {
        if (res.code == 200) this.initPassword = res.msg
      })
      this.getDicts('sys_normal_disable').then((res) => {
        if (res.code == 200) this.enumOpt.stateList = res.data
      })
      getUser().then((res) => {
        if (res.code == 200) this.postOptions = res.posts
      })
      listRole({ pageNum: 1, pageSize: 9999 }).then((res) => {
        if (res.code == 200) {
          res.rows.forEach(item => {
            this.enumOpt.roleList.push({
              dictLabel: item.roleName,
              dictValue: item.roleId,
            })
          })
        }
      })
      this.getDicts("sys_config_level").then((res) => {
        if (res.code == 200) {
          this.levelList = res.data;
        }
      });
      // 查询执行员工
      let params = {
        name: "",
        deptId: null,
        authFlag: "Y",
      };
      permission(params).then((res) => {
        if (res.code === 200 && res.data.length) {
          res.data.forEach((item) => {
            this.enumOpt.staffList.push({
              dictLabel: item.userName,
              dictValue: item.userId,
            });
          });
        }
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((res) => {
        if (res.code == 200) this.enumOpt.manageComList = res.data
      })
    },
    /** 查询用户列表 */
    getTableListFn() {
      this.loading = true
      let params = {
        flag: this.activeTab,
        beginTime: this.queryForm.dateRange?.[0],
        endTime: this.queryForm.dateRange?.[1],
        ...this.queryForm
      }
      delete params['dateRange'];
      listUser(params).then((res) => {
        if (res.code == 200) {
          this.userList = res.rows || []
          this.total = res.total || []
        }
        this.loading = false
      });
    },
    handleTabBefore(activeName, oldActiveName) {
      return !(activeName == 'CustoBtn')
    },
    handleTabClick(e) {
      if (e.name != 'CustoBtn') {
        this.queryForm.pageNum = 1
        this.queryForm.pageSize = 20
        this.getTableListFn()
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.page = 1
      this.getTableListFn()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryForm = {
        userName: '',
        phonenumber: null,
        status: null,
        deptId: null,
        dateRange: [],
        createList: null,
        weUserName: '',
        roleId: null,
        page: 1,
        pageNum: 1,
        pageSize: 20,
      };
      this.getTableListFn()
    },
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.getTableListFn()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.getTableListFn()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.updateVisible = true
      this.title = '添加用户'
      this.scrmPersonSopUserRels = []
      // this.updateForm.password = this.initPassword
      this.updateForm = {
        deptId: null,
        email: '',
        insuranceType: '',
        nickName: '',
        password: '',
        phonenumber: '',
        postIds: [],
        remark: '',
        roleIds: [],
        sex: '',
        status: '',
        userName: '',
        weUserId: '',
        weUserName: '',
        level: '',
      }
      this.$refs.updateForm.resetFields();
    },
    // 取消按钮
    updateCancel() {
      this.updateVisible = false
      this.$refs.updateForm.resetFields();
    },
    /** 新增、修改提交按钮 */
    submitForm() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          this.addingPopover = true
          let params = {
            ...this.updateForm
          }
          if (this.updateForm.userId) {
            params['userId'] = this.updateForm.userId
            updateUser(params).then((response) => {
              if (response.code === 200) {
                this.$message.success('修改成功')
                this.updateVisible = false
                this.handleQuery()
                this.$refs.updateForm.resetFields();
              }
              this.addingPopover = false
            }).catch((err) => {
              this.addingPopover = false
            })
          } else {
            addUser(params).then((response) => {
              if (response.code === 200) {
                this.$message.success('新增成功')
                this.updateVisible = false
                this.handleQuery()
                this.$refs.updateForm.resetFields();
              }
              this.addingPopover = false
            }).catch((err) => {
              this.addingPopover = false
            })
          }
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const userId = row.userId || this.idslet
      getUser(userId).then((res) => {
        this.updateForm = {
          userId,
          deptId: res.data.deptId,
          email: res.data.email,
          insuranceType: res.data.insuranceType,
          nickName: res.data.nickName,
          password: '',
          phonenumber: res.data.phonenumber,
          postIds: res.postIds,
          remark: res.data.remark,
          roleIds: res.roleIds,
          sex: res.data.sex,
          status: res.data.status,
          userName: res.data.userName,
          weUserId: res.data.weUserId,
          weUserName: res.data.weUserName,
          level: res.data.level
        }
        if (res.data.weUserId && res.data.weUserName) {
          this.scrmPersonSopUserRels = [{ userId: res.data.weUserId, userName: res.data.weUserName }]
        }
      })
      this.updateVisible = true
      this.title = '修改用户'
    },
    // 邀请员工
    inviteStaffFn() {
      this.scrmPersonSopUserRels = []
      this.inviteVisible = true
    },
    // 取消按钮
    inviteCancel() {
      this.inviteVisible = false
      this.scrmPersonSopUserRels = []
      this.$refs.inviteForm.resetFields();
    },
    // 保存邀请
    inviteSubmit() {
      this.inviteForm.url = `${window.globalConfig.SHARE_URL}/account?mobile=${this.inviteForm.mobile}`
      this.inviteForm.userId = Cookies.get('UserId')
      this.$refs['inviteForm'].validate((valid) => {
        if (valid) {
          inviteUser(this.inviteForm).then((response) => {
            if (response.code === 200) {
              this.$message.success('新增成功')
              this.inviteVisible = false
              this.$refs.inviteForm.resetFields();
              this.queryForm.flag = 2
              this.getTableListFn()
            }
          })
        }
      })
    },
    // 创建人
    selectOptions(obj) {
      this.queryForm.createList = obj.select[0];
    },
    resetForm,
    // 添加员工-打开弹窗
    openStaff() {
      this.staffDialog = true
      this.selectList = this.scrmPersonSopUserRels || []
    },
    // 添加员工弹窗的确认
    selectUserConfirm(value) {
      if (value && value.length > 1) {
        this.$message.error('只支持选中一个员工')
        this.staffDialog = true
        return
      } else {
        if (value) {
          this.scrmPersonSopUserRels = []
          value.forEach((item) => {
            this.scrmPersonSopUserRels.push({
              ...item
            })
          })
          this.updateForm.weUserId = this.scrmPersonSopUserRels[0].userId;
          this.updateForm.weUserName = this.scrmPersonSopUserRels[0].userName;
          this.inviteForm.weUserId = this.scrmPersonSopUserRels[0].userId;
          this.inviteForm.weUserName = this.scrmPersonSopUserRels[0].userName;
        } else {
          this.scrmPersonSopUserRels = []
        }
        this.staffDialog = false
      }
    },
    // 删除已选人员,执行员工
    handleClose() {
      this.scrmPersonSopUserRels = []
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$confirm(
        '确认要"' + text + '""' + row.userName + '"用户吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return changeUserStatus(row.userId, row.status)
        })
        .then(() => {
          this.$message.success(text + '成功')
        })
        .catch(function () {
          row.status = row.status === '0' ? '1' : '0'
        })
    },
    /** 重置密码按钮操作 */
    changeResPassword(row) {
      this.resetPwdVisible = true
      this.pwdUserId = row.userId
      this.resForm.newPwd = ''
    },
    handleResetPwd() {
      this.$refs['resForm'].validate(valid => {
        if (valid) {
          resetUserPwd({ userId: this.pwdUserId, password: this.resForm.newPwd }).then((response) => {
            if (response.code === 200) {
              this.$message.success('修改成功，新密码是：' + this.resForm.newPwd)
              this.resetPwdVisible = false
            }
          })
        } else {
          this.$message.error('信息还未录入完成，请核对后提交！')
        }
      }).then(() => {
        this.resetPwdVisible = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delUser(userIds)
      }).then(() => {
        this.getTableListFn()
        this.$message.success('删除成功')
      })
    },
  }
}
</script>
<style lang="scss" scoped>
@import "../../../styles/base.scss";

.table-btn>>>.is-disabled {
  color: #ccc !important;
}

.tree-select-user>.vue-treeselect__control {
  width: 100% !important;
}

.app-container {
  height: 100%;
}

.vue-treeselect__control {
  width: 80%;
}

::v-deep .el-tabs__nav {
  width: 100%;
}

::v-deep #tab-CustoBtn {
  width: calc(100% - 228px);
  text-align: right;
  padding-right: 0;
}
</style>
